#pragma once
#include "Log.hpp"
#include "LockGuard.hpp"
#include <iostream>
#include <unordered_map>
#include <fstream>
#include <string>

namespace dict_ns
{
    const std::string defaultpath = "./Dict.txt";
    // const std::string sep = ": ";
    class Dict
    {
    private:
        bool Load()
        {
            // C++方式打开文件
            std::ifstream in(_dict_conf_filepath);
            if (!in.is_open())
            {
                LOG(FATAL, "open %s error \n", _dict_conf_filepath.c_str());
                return false;
            }

            std::string line;
            while (std::getline(in, line))
            {
                if (line.empty())
                    continue;
                // 分隔符查找
                const std::string sep = ": ";
                // 字串查找
                auto pos = line.find(sep); // 这里返回的是sep子串的首字符的下标，这里就是':'的下标
                if (pos == std::string::npos)
                    continue;                           // 没找到子串（分隔符）,说明这一行有问题
                std::string word = line.substr(0, pos); // [0.pos) substr需要前闭后开的区间
                if (word.empty())
                    continue;
                std::string han = line.substr(pos + sep.size()); //  只给substr传一个值，默认找到字符串的最后
                if (han.empty())
                    continue;
                LOG(DEBUG, "load info, %s: %s\n", word.c_str(), han.c_str());

                _dict.insert(std::make_pair(word, han));
            }

            in.close();
            LOG(DEBUG, "load %s success\n", _dict_conf_filepath.c_str());
            return true;
        }

    public:
        Dict(const std::string path = defaultpath) : _dict_conf_filepath(path)
        {
            Load();
        }

        std::string Translate(const std::string &word, bool &ok)
        {
            ok = true;
            auto iter = _dict.find(word);
            if(iter == _dict.end())
            {
                ok = false;
                return "未找到";
            }
            // return _dict[word];
            return iter->second;
        }
        ~Dict() {}

    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_conf_filepath;
    };
}